package com.cdy.common.domain;

import com.cdy.common.uitl.MathUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import static com.cdy.common.property.CommonProperty.BigSectionLength;
import static com.cdy.common.property.CommonProperty.SmallSectionLength;

/**
 * 文件实体
 * Created by 陈东一
 * 2019/10/19 0019 15:17
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class FileEntity extends BaseEntity {

    private static final long serialVersionUID = -3205264898899725614L;
    private String name;
    private String md5;
    private Long length;
    private String location;
    private Boolean complete;

    private static AtomicLong fileIdAddr = new AtomicLong();

    public FileEntity() {
        setId(fileIdAddr.incrementAndGet());
    }

    public List<FileSectionEntity> createSectionTasks(String clientId) {
        int size = MathUtil.divide(getLength(), BigSectionLength);
        ArrayList<FileSectionEntity> fileSectionEntities = new ArrayList<>(size);

        for (int i = 0; i < size; i++) {
            FileSectionEntity sectionEntity = new FileSectionEntity();
            sectionEntity.setBegin((long) i * BigSectionLength);
            long length;
            if (i == size - 1) {
                length = getLength() - i * BigSectionLength;
            } else {
                length = BigSectionLength;
            }
            sectionEntity.setLength(length);
            sectionEntity.setFileId(getId());
            sectionEntity.setComplete(false);
            sectionEntity.setClientId(clientId);
            int sectionSize = MathUtil.divide(length, SmallSectionLength);
            sectionEntity.setSectionSize(sectionSize);
            BitSet bitSet = new BitSet();
            sectionEntity.setBitSet(bitSet);
            fileSectionEntities.add(sectionEntity);
        }
        return fileSectionEntities;
    }
}
